package examination;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import examination.util.JsonUtil;

/**
 * Servlet implementation class ExamQueryServlet
 * @author ChangingSelf
 */
@WebServlet("/ExamQueryServlet")
public class ExamQueryServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ExamQueryServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		 * 查询考试信息数据接口。将数据转为json字符串返回。 
		 * 
		 * 【参数】
		 * method（取值"examNo","staffNo","status"）
		 * examNo
		 * staffNo
		 * status（用request.getParameterValues获取String[]）。
		 * 根据method的取值来调用ExamBean的不同方法得到查询结果
		 */
		request.setCharacterEncoding("UTF-8");
		String method = request.getParameter("method");
		String examNo = request.getParameter("examNo");
		String staffNo = request.getParameter("staffNo");
		String[] statusList = request.getParameterValues("status");
		
		if(method==null) method="";
		
		
		ExamBean[] exams = null;
		switch (method) {
		case "examNo"://按考试号码查找
			exams = new ExamBean[] {
					ExamBean.queryByNo(examNo)
			};
			break;
		case "staffNo"://按职工号码查找
			exams = ExamBean.queryByInvigilator(staffNo);
			break;
		case "status"://按照考试状态查找
			List<ExamBean> examList = new ArrayList<ExamBean>();
			if(statusList!=null) {
				for(String status:statusList) {
					ExamBean[] tempExams=null;
					if(staffNo==null) {
						tempExams = ExamBean.queryByStatus(status);
					}else {
						tempExams = ExamBean.query(String.format("AND exam.exam_status='%s' AND teacher_id='%s'", status,staffNo));
					}
					if(tempExams!=null) {
						for(ExamBean tempExam:tempExams) {
							examList.add(tempExam);
						}
					}
				}
			}
			exams =examList.toArray(new ExamBean[examList.size()]);
			break;
		default://其他情况均返回全部考试信息
			exams = ExamBean.queryAll();
			break;
		}
		String jsonString = JsonUtil.toLayuiTableJson(exams);
		
		// 响应参数格式设置，并将json字符串写入响应
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().print(jsonString);
	}

}
